using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;

namespace Hermes.Framework.FileSystem
{
    public class Url
    {
        public static int DEFAULT_PORT = 0;

        protected string host;

        protected string file;

        protected string protocol;

        protected string directory;

        protected int port;

        public Url(string url)
        {
            Console.WriteLine(string.Format("URL: {0}", url));
            this.protocol = FileSystemUtils.GetProtocol(url);
            int slash;
            int colon = url.IndexOf(":");
            if (colon == -1)
            {
                throw new ArgumentException(string.Format("Url does not have a protocol."));
            }
            this.protocol = url.Substring(0, colon);
            slash = url.IndexOf('/', colon + 3);
            Console.WriteLine(url);
            string hostAndPort = url.Substring(colon + 3, slash - colon - 3);
            colon = hostAndPort.IndexOf(':');
            
            if (colon == -1)
            {
                object defaultPort = ConfigurationSettings.AppSettings["defaultPort"];
                if (defaultPort == null)
                {
                    this.port = DEFAULT_PORT;
                }
                else
                {
                    this.port = Int32.Parse(defaultPort.ToString());
                }
                this.host = hostAndPort;
            }
            else
            {
                this.host = hostAndPort.Substring(0, colon);
                this.port = Int32.Parse(hostAndPort.Substring(colon + 1));
            }
            int slash1 = url.LastIndexOf('/');
            if (slash1 == slash)
            {
                this.directory = "/";
                this.file = "";
            }
            else
            {
                this.directory = url.Substring(slash + 1, slash1 - slash - 1);
                this.file = url.Substring(slash1 + 1);
            }
        }

        public string Protocol
        {
            get
            {
                return this.protocol;
            }
        }

        public string Host
        {
            get
            {
                return this.host;
            }
        }

        public string File
        {
            get
            {
                return this.file;
            }
        }

        public string Directory
        {
            get
            {
                return this.directory;
            }
        }

        public int Port
        {
            get
            {
                return this.port;
            }
        }
    }
}
